package com.example.lottery.service.activitystatus.operator;

import com.example.lottery.dao.dataobject.ActivityDO;
import com.example.lottery.dao.dataobject.ActivityPrizeDO;
import com.example.lottery.dao.mapper.ActivityMapper;
import com.example.lottery.dao.mapper.ActivityPrizeMapper;
import com.example.lottery.service.dto.ConvertActivityStatusDTO;
import com.example.lottery.service.enums.ActivityPrizeEnum;
import com.example.lottery.service.enums.ActivityUserEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ActivityOperator extends AbstractOperator{
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;
    @Override
    public Integer sequence() {
        return 2;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        //1-    校验参数，目标状态是否为空 是否为COMPLETE
        if(convertActivityStatusDTO==null||
                convertActivityStatusDTO.getTargetActivityStatus()==null
                ||!convertActivityStatusDTO.getTargetActivityStatus().name().equalsIgnoreCase(ActivityUserEnum.COMPLETE.name())){
            log.warn("参数、目标状态错误");
            return false;
        }

        //2-    判断活动是否为空
        Long activityId = convertActivityStatusDTO.getActivityId();
        if(activityId==null){
            log.warn("奖品为空");
            return false;
        }
        try {
            //3-    判断活动表中是否存在记录
            if(activityMapper.selectByPrimaryKey(convertActivityStatusDTO.getActivityId())==null){
                log.warn("活动表中不存在该条记录");
                return false;
            }
        }catch (Exception e){
            //sql异常
            log.warn("sql查询活动表记录异常");
            return false;
        }
        //3-    判断关联的所有奖品是否都为COMPLETE
        try{
            int i=activityPrizeMapper.selectPrizeStatus(convertActivityStatusDTO.getActivityId()
                    , ActivityPrizeEnum.INIT.name());
            if(i>0){
                //说明奖品存在状态为：INIT记录
                return false;
            }
        }catch (Exception e){
            //sql异常
            log.warn("sql selectPrizeStatus 查询奖品状态异常");
            return false;
        }
        return true;
    }

    @Override
    public Boolean convertStatus(ConvertActivityStatusDTO convertActivityStatusDTO) {
        //1-    开始扭转
        try{
            int i=activityMapper.updateStatus(convertActivityStatusDTO.getActivityId(),convertActivityStatusDTO.getTargetActivityStatus().name());
            if(i==0){
                log.warn("活动扭转失败");
                return false;
            }
        }catch (Exception e){
            //sql异常
            log.warn("sql扭转活动状态异常");
            return false;
        }
        return true;
    }
}
